package demo02.util;


import demo02.model.Agent;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.math.BigInteger;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Date;

public class ConnectDb {  
    private static String driveClassName = "com.mysql.jdbc.Driver";  
    private static String url = "jdbc:mysql://localhost:3306/wo?useUnicode=true&characterEncoding=utf8";
      
    private static String user = "root";  
    private static String password = "root";

    static Connection conn = null;
      
    public static Connection Connect(){
          
        //load driver  
        try {  
            Class.forName(driveClassName);  
        } catch (ClassNotFoundException  e) {  
            System.out.println("load driver failed!");  
            e.printStackTrace();  
        }  
          
        //connect db  
        try {
            if(conn == null) {
                conn = DriverManager.getConnection(url, user, password);
            }
        } catch (SQLException e) {  
            System.out.println("connect failed!");  
            e.printStackTrace();  
        }
        return conn;  
    }  
    
    public static void main(String[] args){
        Connection connection = Connect();
        QueryRunner queryRunner = new QueryRunner();
        String sql = "insert into agent values(null, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        Agent agent = new Agent();
        agent.setCreateTime(new Date());
        try {
            queryRunner.update(connection, sql, new Object[]{
                    agent.getAgentName(),
                    agent.getTel(),
                    agent.getCorp(),
                    agent.getDept(),
                    agent.getAvatarUrl(),
                    agent.getUrl(),
                    agent.getCityId(),
                    agent.getNet(),
                    agent.getOriginUserId(),
                    agent.getZone(),
                    agent.getSection(),
                    agent.getCreateTime(),
                    agent.getCorpId(),
                    agent.getUserId()
            });
            BigInteger id =  queryRunner.query(conn, "SELECT LAST_INSERT_ID()", new ScalarHandler<BigInteger>(1));
            System.out.println("----------=" + id.longValue());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
} 